package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import utilities.Logger;

public class LoginManagerHSQLDB implements LoginManager {

	private static LoginManagerHSQLDB lm;
	private Connection c;
	private static Logger log = Logger.getLogger( LoginManagerHSQLDB.class );
	
	/**
	 * Creates new instance of LoginManagerHSQLDB
	 * @throws DAOException Thrown if database-connection fails.
	 */
	protected LoginManagerHSQLDB() throws DAOException {
		DatabaseManager dbm = DatabaseManager.getInstance();
		try {
			c = dbm.getConnection();
		} catch (NullPointerException e) {
			throw new DAOException("No Connection.");
		}
		lm = this;
		log.d("Instance created.");
	}

	/**
	 * Returns a new / existing instance of LoginManagerHSQLDB
	 * @return Instance of LoginManagerHSQLDB
	 * @throws DAOException In case of SQL / connection errors.
	 */
	public static LoginManager getInstance() throws DAOException  {

		if (lm == null) {
				return new LoginManagerHSQLDB();
		}
		return lm;
		
	}
	
	/**
	 * @see LoginManager#logIn(String, String)
	 */
	@Override
	public boolean logIn(String uid, String password) throws DAOException {
		try {
			String query = "SELECT password FROM user WHERE uid = ?";
			PreparedStatement stmt;
			stmt = c.prepareStatement(query);
			stmt.setString(1, uid);
			ResultSet rs = stmt.executeQuery();
		
			boolean retVal = false;
			
			if (rs.next()) {
				retVal = password.equals(rs.getString(1));
			}

			stmt.close();
			rs.close();
			
			return retVal;
		} catch (SQLException e) {
			throw new DAOException(e.getMessage());
		}
	}

}
